package org.ghost.spring.cloud.hystrix.demo.common.filter;

import org.ghost.spring.cloud.hystrix.demo.common.component.RequestContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

public class RequestUUIDFilter implements Filter {

    public static final String REQUEST_HEADER_NAME = "X-REQUEST-UUID";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {

        // uuid埋点
        uuidBuried((HttpServletRequest) req);

        chain.doFilter(req, res);
    }

    /**
     * uuid埋点
     *
     * @param request
     */
    private void uuidBuried(HttpServletRequest request) {
        HttpServletRequest httpServletRequest = request;
        String id = httpServletRequest.getHeader(REQUEST_HEADER_NAME);

        if (id == null || "".equals(id)) {
            id = UUID.randomUUID().toString();
        }

        RequestContext.getContext().setId(id);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
